const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  const result = await db.collection("token").get()
  var resultIndex = await cloud.callFunction({name: 'getIndex'})
  
  var curTime = new Date().getTime()
  if (result.errMsg == "collection.get:ok") {
    console.log("token===", JSON.stringify(result.data))
    if (result.data.length > 0) {
      var token = result.data[0].token
      if (token) {
        var time = result.data[0].ctime
        var timeInt = 0
        if (time) {
          timeInt = parseInt(time)
        }
        var timeDayNum = parseInt((curTime - timeInt) / (1000 * 60 * 60 * 24))
        if (timeDayNum > 28) {
          const res = await cloud.callFunction({
            name: 'getBaiduAccessToken',
          })
          console.log("res===", JSON.stringify(res))
          await db.collection("token").add({
            data: {
              "token": res.result.data.access_token,
              "ctime": curTime
            }
          })
          return {token:res.result.data.access_token,resultIndex}
        }
        else {
          return {token:token,resultIndex} 
        }
      } else {
        const res = await cloud.callFunction({
          name: 'getBaiduAccessToken',
        })
        console.log("res===", JSON.stringify(res))
        await db.collection("token").add({
          data: {
            "token": res.result.data.access_token,
            "ctime": curTime
          }
        })
        return {token:res.result.data.access_token,resultIndex}
      }
    } else {
      const res = await cloud.callFunction({
        name: 'getBaiduAccessToken',
      })
      console.log("res===", JSON.stringify(res))
      await db.collection("token").add({
        data: {
          "token": res.result.data.access_token,
          "ctime": curTime
        }
      })
      return {token:res.result.data.access_token,resultIndex}
    }
  } else {
    const res = await cloud.callFunction({
      name: 'getBaiduAccessToken',
    })
    console.log("res===", JSON.stringify(res))
    await db.collection("token").add({
      data: {
        "token": res.result.data.access_token,
        "ctime": curTime
      }
    })
    return {token:res.result.data.access_token,resultIndex}
  }
}